package com.smt.take.presenter

import android.content.Context
import android.widget.Toast
import com.itkacher.okhttpprofiler.OkHttpProfilerInterceptor
import com.smt.take.BuildConfig
import com.smt.take.model.net.BaseResponse
import com.smt.take.model.net.TakeOutService
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory

abstract class BasePresenter<T>(context: Context?) {

    val takeOutService: TakeOutService

    init {
        val builder = OkHttpClient.Builder()
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(OkHttpProfilerInterceptor())
        }
        val client = builder.build()
        val retrofit = Retrofit.Builder()
            .baseUrl("http://192.168.110.104:8080/")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .client(client)
            .build()

        takeOutService = retrofit.create<TakeOutService>(TakeOutService::class.java)
    }

    abstract fun setDataToUI(data: T?)

    val callback = object : Callback<BaseResponse<T>> {
        override fun onResponse(
            call: Call<BaseResponse<T>>?,
            baseResponse: Response<BaseResponse<T>>?
        ) {
            // 连接成功
            if (baseResponse == null) {
                Toast.makeText(context, "服务器没有返回成功", Toast.LENGTH_SHORT).show()
            } else {
                if (baseResponse.isSuccessful) {
                    val responseInfo = baseResponse.body()
                    when (responseInfo?.code) {
                        //根据具体的接口文档表示含义，比如定义0为成功，-1为空数据
                        "0" -> {
                            setDataToUI(responseInfo.data)
                        }

                        "-1" -> {
                            Toast.makeText(context, "数据为空", Toast.LENGTH_SHORT)
                                .show()
                        }
                    }
                } else {
                    Toast.makeText(context, "服务器出现错误", Toast.LENGTH_SHORT).show()
                }
            }

        }

        override fun onFailure(call: Call<BaseResponse<T>>?, t: Throwable?) {
            //没有连上服务器
            Toast.makeText(context, "服务器连接失败", Toast.LENGTH_SHORT).show()
        }

    }

}